﻿using System;
using Newtonsoft.Json;
using WeiXin.Lib.Core.Helper;

namespace WeiXin.Lib.WCF.Model
{
    public sealed class JsApiTicket
    {
        private static object lock_Object = new object();

        [JsonProperty("Ticket")]
        public string Ticket { get; set; }

        /// <summary>
        /// 有效时间，秒
        /// </summary>
        [JsonProperty("expires_in")]
        public int ExpiresIn { get; set; } = -1;

        private DateTime CreateTime;

        private JsApiTicket()
        {
            
        }


        private static JsApiTicket _instance= new JsApiTicket();

        public static JsApiTicket Instance
        {
            get
            {
                if (_instance.Expired)
                {
                    lock (lock_Object)
                    {
                        if (_instance.Expired)
                        {
                            _instance.CopyModel(GetTicket());
                        }
                    }
                }

                return _instance;
            }
        }

        private static JsApiTicket GetTicket()
        {
            var ticket = WeiXinHelper.CreateJsApiTicketAsync().Result;
            return new JsApiTicket {CreateTime = DateTime.Now,Ticket = ticket,ExpiresIn = 7200};
        }

        public bool Expired
        {
            get
            {
                if (ExpiresIn < 0) return true;
                DateTime expiredTime = CreateTime.AddSeconds(ExpiresIn - 200);

                if (DateTime.Now > expiredTime)
                    return true;

                return false;
            }
        }

        public void CopyModel(JsApiTicket token)
        {
            //token 为空，将 过期时间 设置为 -1
            if (token == null)
            {
                this.ExpiresIn = -1;
                return;
            }

            this.Ticket = token.Ticket;
            this.ExpiresIn = token.ExpiresIn;

        }
    }
}